package edu.seu.mart.service.impl;


import edu.seu.mart.dao.IknowledgeDao;
import edu.seu.mart.dao.IknowledgeSubDao;
import edu.seu.mart.entity.Pager;
import edu.seu.mart.model.Knowledge;
import edu.seu.mart.model.MartException;
import edu.seu.mart.service.IChatService;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.stereotype.Service;
import org.wltea.analyzer.lucene.IKAnalyzer;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;

/**
 * Created by asus on 2015/3/20.
 */
@Service
public class ChatService implements IChatService {

    @Resource
    IknowledgeDao knowledgeDao;

    @Resource
    IknowledgeSubDao knowledgeSubDao;

    @Override
    public List<Knowledge> findAllKnowledge() {
        return knowledgeDao.findAllKnowledge();
    }

    @Override
    public String getKnowledgeSub(int knowdgeId) {
        return knowledgeSubDao.getKnowledgeSub(knowdgeId);
    }

    public String getIndexDir() {
        String classpath = ChatService.class.getResource("/").getPath();
        classpath = classpath.replaceAll("20%", " ");
        return classpath + "chat/";
    }

    @Override
    public String chat(String question) {
        String answer = null;
        Knowledge knowledge = searchIndex(question);
        if (null != knowledge) {
            if (knowledge.getAnswer() == null || "".equals(knowledge.getQuestion())) {
                answer = getKnowledgeSub(knowledge.getId());
            } else {
                answer = knowledge.getAnswer();
            }
        } else {
            answer = getDefaultAnswer();
        }
        return answer;
    }

    @Override
    public Knowledge load(int knowledgeId) {
        return knowledgeDao.load(knowledgeId);
    }

    @Override
    public void update(Knowledge knowledge) {
        knowledgeDao.update(knowledge);
    }

    @Override
    public void save(Knowledge knowledge) {
        knowledgeDao.add(knowledge);
    }

    @Override
    public void delete(int knowledgeId) {

        knowledgeDao.delete(knowledgeId);
    }

    @Override
    public Pager<Knowledge> findAllPagerKnowledge() {
        return knowledgeDao.findAllPagerKnowledge();
    }

    public void creatIndexDir() {
        List<Knowledge> knowledgeList  = this.findAllKnowledge();
        Directory directory = null;
        IndexWriter indexWriter = null;
        try {
            directory = FSDirectory.open(new File(getIndexDir()));
            IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_46, new IKAnalyzer(true));
            indexWriter = new IndexWriter(directory, iwConfig);
            Document doc = null;
            for (Knowledge knowledge : knowledgeList) {
                doc = new Document();
                doc.add(new TextField("question", knowledge.getQuestion(), Field.Store.YES));
                doc.add(new IntField("id", knowledge.getId(), Field.Store.YES));
                doc.add(new StringField("answer", knowledge.getAnswer(), Field.Store.YES));
                indexWriter.addDocument(doc);
            }
            indexWriter.close();
            directory.close();
        } catch (IOException e) {
            throw new MartException(e);
        }
    }

    public Knowledge searchIndex(String content) {
        Knowledge knowledge = null;
        try {
            Directory directory = FSDirectory.open(new File(this.getIndexDir()));
            IndexReader reader = IndexReader.open(directory);
            IndexSearcher searcher = new IndexSearcher(reader);
            QueryParser queryParser = new QueryParser(Version.LUCENE_46,"question", new IKAnalyzer(true));
            Query query = queryParser.parse(QueryParser.escape(content));
            TopDocs topDocs = searcher.search(query, 1);
            if (topDocs.totalHits > 0) {
                knowledge = new Knowledge();
                ScoreDoc[] scoreDocs = topDocs.scoreDocs;
                for (ScoreDoc sd : scoreDocs) {
                    Document doc = searcher.doc(sd.doc);
                    knowledge.setId(doc.getField("id").numericValue().intValue());
                    knowledge.setQuestion(doc.get("question"));
                    knowledge.setAnswer(doc.get("answer"));
                }
            }
            reader.close();
            directory.close();
        } catch (Exception e) {
            knowledge = null;
            e.printStackTrace();
        }
        return knowledge;
    }

    public String getDefaultAnswer() {
        String []answer = {
                "嗯？你到底在说什么呢",
                "没用听懂你说的，能否换个说法？",
                "虽然不明白你的意思，但我却能用心去感受",
                "哎，我语文是数学老师交的，理解起来好困难哦",
                "听得我一头雾水，阁下的知识真是渊博啊，膜拜"
        };
        return answer[getRandomNumber(answer.length)];
    }

    private static int getRandomNumber(int length) {
        Random random = new Random();
        return random.nextInt(length);
    }
}
